<template>
	<view style="height: 100%" @click="hideCopyBtn">
		<view class="page">
			<scroll-view class="box-msg-list" :scroll-x="false" :scroll-y="true" :scroll-with-animation="true" :scroll-top="scrollTop" @scroll="onListScroll">
				<view class="list" v-if="lists && lists.length > 0">
					<view class="message-group" v-for="(item, index) in lists" :key="index">
						<view class="message user">
							<view class="avatar">
								<img mode="widthFix" :src="userAvatar" />
							</view>
							<view class="text" @longpress="showCopyBtn" :data-text="item.message">
								<textComponent :text="item.message"></textComponent>
								<view class="tools">
									<view class="btn" @click="replayOptions(item.draw_id)">
										<image class="icon" src="/static/images/ic_copy.png"></image>
										<span>{{ '复用参数' | lang }}</span>
									</view>
									<text style="font-size: 13px; color: #898989;">{{ item.create_time }}</text>
								</view>
							</view>
						</view>
						<view class="message ai">
							<view class="avatar">
								<img mode="widthFix" src="/static/img/ic_ai.png" />
							</view>
							<view class="text">
								<imageComponent :item="item" @preview="previewImage" @retry="retryDraw">
								</imageComponent>
							</view>
						</view>

					</view>

					<view class="btn-copy" :style="'left:' + copyBtnLeft +'px;top:' + copyBtnTop + 'px;'" @tap="copyText(copyBtnText)">{{ '复制' | lang }}</view>
				</view>
				<view v-else class="welcome">
					<view class="nodata">
						<image mode="widthFix" src="/static/images/ic_nodata.png"></image>
						<view class="tips">您还没有作品，快去创作吧</view>
					</view>
					
					<button class="btn-create" @tap="showDrawSetting">
						<image src="/static/images/ic_draw_white.png"></image>
						<text>新建绘画</text>
					</button>
				</view>
			</scroll-view>
			
			<button v-if="lists && lists.length > 0" class="btn-create" :class="{mini: createButtonType === 'mini'}" @tap="showDrawSetting" :style="'bottom:' + (safeAreaHeight + 140) + 'rpx;'">
				<image src="/static/images/ic_draw_white.png"></image>
				<text v-if="createButtonType === 'mini'">新建</text>
				<text v-else>新建绘画</text>
			</button>
		</view>
		<popup ref="drawPopup" mode="bottom" title="新建绘画" top="200rpx" bottom="50px">
			<scroll-view class="box-setting" :scroll-x="false" :scroll-y="true" :scroll-with-animation="false" :scroll-top="settingScrollTop">
				<drawMj ref="drawSetting" v-if="setting['platform'] === 'mj'"></drawMj>
				<drawOpenai ref="drawSetting" v-else-if="setting['platform'] === 'openai'"></drawOpenai>
				<drawYijian ref="drawSetting" v-else-if="setting['platform'] === 'other' && setting['channel'] === 'yijian'" :settings="setting['options']"></drawYijian>
				<view class="share">
					<picker @change="drawCatePick" :value="activeDrawCate.index" :range="drawCatePickArr">
						<view class="picker">
							<text v-if="activeDrawCate.title">{{activeDrawCate.title}}</text>
							<text v-else style="color: #999;">请选择图片分类</text>
							<image class="ic_down" src="/static/images/ic_picker_down.png"></image>
						</view>
					</picker>
					<view class="agree">
						<label>
							<checkbox-group @change="isShareChange">
								<checkbox value="1" :checked="is_share" color="#04BABE" activeBorderColor="#04BABE"></checkbox>
							<text>共享到图库</text>
							</checkbox-group>
						</label>
					</view>
				</view>
				<view class="submit">
					<button class="btn-submit" @tap="submitDraw">开始绘画</button>
				</view>
			</scroll-view>
		</popup>
	</view>
</template>

<script>
	const app = getApp();
	import TextComponent from '../../components/message/text'
	import ImageComponent from '../../components/message/image'
	import drawMj from '../../components/draw/mj'
	import drawOpenai from '../../components/draw/openai'
	import drawYijian from '../../components/draw/yijian'
	import 'katex/dist/katex.min.css'
	import '../../static/styles/lib/tailwind.css'
	import '../../static/styles/lib/highlight.scss'
	import '../../static/styles/lib/github-markdown.scss'
	
	export default {
		components: {
			TextComponent,
			ImageComponent,
			drawMj,
			drawOpenai,
			drawYijian
		},
		data() {
			return {
				isLogin: false,
				siteroot: '',
				lists: [],
				message: '',
				page: 1,
				pagesize: 10,
				scrollTop: 0,
				createButtonType: 'big',
				inputShow: true,
				copyBtnLeft: -200,
				copyBtnTop: 0,
				copyBtnText: '',
				copyBtnTime: 0,
				setting: {},
				drawCates: [],
				drawCatePickArr: [],
				activeDrawCate: {},
				is_share: true,
				options: {},
				settingScrollTop: 0,
				safeAreaHeight: 0,
				submiting: false
			};
		},
		computed: {
			userAvatar() {
				if (this.userinfo && this.userinfo.avatar) {
					return this.userinfo.avatar
				} else {
					return '/static/img/ic_user.png'
				}
			}
		},
		onLoad(options) {
			this.setData({
				system: app.globalData.system,
				siteroot: app.globalData.siteroot.replace('/web.php', ''),
				safeAreaHeight: app.globalData.safeAreaHeight
			});
			app.globalData.util.getSetting().then(setting => {
				this.getDrawSetting();
			})
			app.globalData.util.checkLogin().then(() => {
				this.getHistoryMsg();
				this.setData({
					isLogin: true
				});
				this.getUserInfo();
			});
			this.getDrawCate();
		},
		onShow() {
			uni.setNavigationBarTitle({
				title: this.$lang('AI绘画')
			})
		},
		methods: {
			submitDraw() {
				if (this.submiting) {
					return
				}
				if (!this.isLogin) {
					app.globalData.util.toLogin('请登录')
					return
				}
				let options = this.getDrawOptions()
				if (!options.words || options.words.length <= 0) {
					app.globalData.util.message('请添加画面描述')
					this.setData({
						settingScrollTop: Math.random()
					})
					return
				}
				if (this.drawCates.length > 0 && !this.activeDrawCate.id) {
					app.globalData.util.message('请选择图片分类')
					return
				}
				
				this.submiting = true

				app.globalData.util
					.request({
						url: '/draw/draw',
						data: {
							platform: this.setting['platform'],
							channel: this.setting['channel'],
							cate_id: this.activeDrawCate.id,
							is_share: this.is_share ? 1 : 0,
							options: JSON.stringify(options)
						}
					})
					.then(res => {
						this.submiting = false
						this.closeDrawSetting()
						this.lists.push({
							state: this.setting['platform'] === 'mj' ? 0 : 3,
							draw_id: res.data.draw_id,
							message: res.data.message,
							create_time: res.data.create_time,
							platform: this.setting['platform']
						})
						
						this.clearDrawOptions()
						this.startLoopResult(res.data.draw_id);

						this.scrollToBottom()
					})
					.catch(res => {
						this.submiting = false
						if (res.message.indexOf('请充值') !== -1) {
							app.globalData.util.message(res.message, 'error', function() {
								uni.navigateTo({
									url: '/pages/pay/pay?type=point'
								})
							});
						}
					})
			},

			getDrawOptions() {
				let options = {}
				if (this.$refs.drawSetting) {
					options = this.$refs.drawSetting.getDrawOptions()
				}
				return options
			},
			clearDrawOptions() {
			  if (this.$refs.drawSetting) {
				this.$refs.drawSetting.clearDrawOptions()
			  }
			},

			startLoopResult(draw_id) {
				var si = setInterval(() => {
					app.globalData.util
						.request({
							url: '/draw/getDrawResult',
							data: {
								draw_id: draw_id
							},
							loading: false
						})
						.then(res => {
							var lists = this.lists
							lists.forEach((item, index) => {
								if (item.draw_id == draw_id) {
									var state = res.data.state
									lists[index].state = state
									if (state === 3) {
										lists[index].response = [res.data.image]
									} else if (state !== 0) {
										if(state === 1) {
											lists[index].response = res.data.images
											clearInterval(si)
										}
										else if(state === 2) {
											lists[index].errmsg = res.data.message
											clearInterval(si)
										}
										setTimeout(() => {
											this.getUserBalance()
										}, 300)
									}
									this.lists = lists
								}
							})
						});
				}, 5000)
			},

			retryDraw(draw_id) {
				app.globalData.util
					.request({
						url: '/draw/draw',
						data: {
							draw_id: draw_id
						}
					})
					.then((res) => {
						var lists = this.lists
						lists.forEach((item, index) => {
							if (item.draw_id == draw_id) {
								lists[index].state = this.setting['platform'] === 'mj' ? 0 : 3
								lists[index].errmsg = ''
								lists[index].response = ''
								this.startLoopResult(draw_id)
							}
						})
						this.lists = lists
					})
			},

			getDrawSetting() {
				app.globalData.util
					.request({
						url: '/draw/getDrawSetting'
					})
					.then((res) => {
						this.setData({
							setting: res.data
						})
					});
			},
			getDrawCate() {
				app.globalData.util
					.request({
						url: '/draw/getDrawCate'
					})
					.then((res) => {
						let drawCates = res.data
						let pickArr = []
						drawCates.forEach(item => {
							pickArr.push(item.title)
						})
						this.drawCatePickArr = pickArr
						this.drawCates = drawCates
					});
			},

			getHistoryMsg() {
				app.globalData.util
					.request({
						url: '/draw/getHistoryMsg',
						data: {
							page: this.page,
							pagesize: this.pagesize
						}
					})
					.then((res) => {
						if (res.data.length > 0) {
							var lists = res.data
							this.setData({
								lists: lists
							});
							lists.forEach((item, index) => {
								if (item.state == 0) {
									this.startLoopResult(item.draw_id);
								}
							})
						}
						this.scrollToBottom();
					});
			},

			scrollToBottom() {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('.list').boundingClientRect((res) => {
						if (res) {
							this.setData({
								scrollTop: parseInt(res.height)
							});
						}
					});
					query.exec((res) => {});
				}, 500);
			},

			copyText(text) {
				let textarea = document.createElement("textarea");
				textarea.value = text;
				textarea.readOnly = "readOnly";
				textarea.style = "width:0;height:0;";
				document.body.appendChild(textarea);
				textarea.select();
				textarea.setSelectionRange(0, text.length);
				app.globalData.util.message('已复制');
				document.execCommand("copy");
				textarea.remove();
				this.hideCopyBtn()
			},

			showCopyBtn(e) {
				let query = uni.createSelectorQuery().in(this);
				query.select('.list').boundingClientRect((res) => {
					if (res) {
						let x = parseInt(e.touches[0].pageX);
						let y = parseInt(e.touches[0].pageY - res.top);
						if (e.touches[0].pageY < 110) {
							y = y + 120
						}
						this.copyBtnLeft = x - 30;
						this.copyBtnTop = y - 60;
						this.copyBtnText = e.currentTarget.dataset.text;
						this.copyBtnTime = this.getTime()
					}
				});
				query.exec((res) => {});
			},
			getTime() {
				return new Date().getTime()
			},
			hideCopyBtn() {
				const now = this.getTime()
				if (this.copyBtnLeft > 0 && now - this.copyBtnTime > 500) {
					this.copyBtnLeft = -200;
					this.copyBtnText = '';
					this.copyBtnTime = 0
				}
			},

			previewImage(src) {
				var urls = []
				this.lists.forEach((item, index) => {
					if (item.state == 1) {
						item.response.forEach((img, idx) => {
							urls.push(img)
						})
					}
				})
				uni.previewImage({
					urls: urls,
					current: src
				})
			},

			trim(str) {
				if (str) {
					return str.replace(/(^\s*)|(\s*$)/g, '');
				} else {
					return ''
				}
			},

			toEdit(message) {
				this.message = message
			},

			getUserInfo() {
				app.globalData.util
					.request({
						url: '/user/info',
						loading: false
					})
					.then((res) => {
						this.setData({
							userinfo: res.data
						});
					}).catch(res => {

					})
			},
			showDrawSetting() {
				this.$refs.drawPopup.open()
			},
			closeDrawSetting() {
				this.$refs.drawPopup.close()
			},
			isShareChange(e) {
				if (e.detail.value.length > 0) {
					this.is_share = true
				} else {
					this.is_share = false
				}
			},
			drawCatePick(e) {
				let index = e.detail.value
				let activeDrawCate = this.drawCates[index]
				activeDrawCate.index = index
				this.activeDrawCate = activeDrawCate
			},
			replayOptions(draw_id) {
				app.globalData.util
					.request({
						url: '/draw/getDrawOptions',
						data: {
							draw_id: draw_id
						}
					})
					.then((res) => {
						this.showDrawSetting()
						if (res.data.cate_id && this.drawCates.length > 0) {
							this.drawCates.forEach(item => {
								if (item.id === res.data.cate_id) {
									this.activeDrawCate = item
								}
							})
						}
						this.is_share = true
						setTimeout(() => {
							this.$refs.drawSetting.setDrawOptions(res.data.options)
						}, 100)
					})
			},
			mjCtrl(draw_id, type, index) {
				app.globalData.util
					.request({
						url: '/draw/mjCtrl',
						data: {
							draw_id: draw_id,
							type: type,
							index: index
						}
					}).then(res => {
						this.lists.push({
							state: 0,
							draw_id: res.data.draw_id,
							message: res.data.message,
							platform: this.setting['platform']
						})
						this.startLoopResult(res.data.draw_id)
						this.getUserBalance()
						setTimeout(() => {
							this.scrollBottom()
						}, 500)
					})
			},
			onListScroll(e) {
				let scrollTop = e.detail.scrollTop
				if (this.scrollTop - scrollTop > 100) {
					this.scrollTop = scrollTop
					return
				}
				if (scrollTop < this.scrollTop) {
					if (scrollTop < this.scrollTop - 50) {
						this.createButtonType = 'mini'
						this.scrollTop = scrollTop
					}
				} else {
					if (scrollTop > this.scrollTop + 50) {
						this.createButtonType = 'big'
						this.scrollTop = scrollTop
					}
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.welcome {
	    margin-top: 360rpx;
	    position: relative;
	    height: 660rpx;
		.nodata {
		    width: 600rpx;
		    margin: 0 auto;
		    text-align: center;
		    display: flex;
		    flex-direction: column;
		    align-items: center;
			image {
			    width: 300rpx;
			    height: 300rpx;
			}
			.tips {
			    width: 100%;
			    color: #8d9393;
			    font-size: 32rpx;
			    margin-top: 40rpx;
			}
		}
		.btn-create {
		    position: absolute;
		    box-shadow: none;
		    background: #04babe;
		    color: #fff;
		    bottom: 20rpx;
		}
	}

	.box-input {
		width: 100%;
		padding: 40rpx 30rpx;
		left: 0;
		bottom: 0;
		background: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;
		border-top: 1px solid #eee;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		box-shadow: 0 0 20rpx rgba(100, 100, 100, 0.05);
	}
	
	.btn-create {
		width: 44%;
		height: 88rpx;
		border-radius: 44rpx;
		display: flex; 
		justify-content: center;
		align-items: center;
		font-size: 34rpx;
		color: #fff;
		position: fixed;
		right: 28%;
		bottom: 140rpx;
		background: #04BABE;
		box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.1);
		z-index: 1;
		transition: all 0.15s linear;
		overflow: hidden;
	
		image {
			width: 46rpx;
			height: 46rpx;
			margin-right: 10rpx;
			transition: all 0.1s linear;
		}
		text {
			line-height: 32rpx;
			transition: all 0.1s linear;
			white-space: nowrap;
		}
		
		&.mini {
			width: 108rpx;
			height: 108rpx;
			border-radius: 50%;
			flex-direction: column;
			font-size: 24rpx;
			right: 30rpx;
			margin: 0;
			
			image {
				margin-right: 0;
			}
		}
	}

	.page {
		width: 100%;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
	}

	.box-msg-list {
		width: 100%;
		height: 100%;
		top: 0;
		bottom: 132rpx;
		left: 0;
		box-sizing: border-box;
		overflow: hidden;
	}

	.list {
		width: 100%;
		height: auto;
		padding-bottom: 180rpx;
		box-sizing: border-box;
		
		.nomore {
			width: 100%;
			height: 140rpx;
			text-align: center;
			font-size: 24rpx;
			color: #bbb;
			line-height: 100rpx;
		}
	}

	.message-group {
		background: rgba(255, 255, 255, 0.8);
		margin: 40rpx 30rpx 0 30rpx;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.message {
		display: flex;
		justify-content: flex-start;
		padding: 40rpx 40rpx;
	}

	.message.user {
		border-bottom: 2rpx solid #f6f6f6;
		padding-bottom: 30rpx;
	}
	.message.ai {
		padding-top: 30rpx;
	}

	.message .text {
		width: 100%;
		color: #343541;
		line-height: 52rpx;
		font-size: 32rpx;
		word-break: break-all;
		padding: 3rpx 0;
		overflow: hidden;
	}

	.message .text span {
		display: inline;
	}

	.message .avatar {
		width: 58rpx;
		height: 58rpx;
		background: #04BABE;
		margin-right: 30rpx;
		color: #fff;
		font-size: 28rpx;
		border-radius: 4rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 6rpx;
		overflow: hidden;
	}

	.message .avatar image,
	.message .avatar img {
		width: 58rpx;
		height: 58rpx;
	}
	
	
	.tools {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 12rpx;
	}
	
	.tools .btn {
		font-size: 32rpx;
		color: #04BABE;
		display: flex;
		align-items: center;
		float: left;
		margin: 0;
		padding: 0;
		margin-right: 20rpx;
	}
	
	.tools .btn:active {
		opacity: 0.6;
	}
	
	.tools .btn .icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 6rpx;
	}

	/* Animation */
	@keyframes cursor {
		50% {
			background: white;
		}
	}

	.btn-copy {
		position: absolute;
		width: 120rpx;
		height: 60rpx;
		line-height: 60rpx;
		color: #04BABE;
		z-index: 99;
		background: #fff;
		text-align: center;
		border-radius: 10rpx;
		font-size: 28rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);
	}

	.box-setting {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		right: 0;
		padding: 0 30rpx;
		box-sizing: border-box;

		.share {
			display: flex;
			align-items: center;

			.agree {
				margin-left: 30rpx;

				checkbox {
					transform: scale(0.7);
				}

				text {
					font-size: 28rpx;
					color: #999;
				}
			}

			.picker {
				background: #f7f7f8;
				width: 360rpx;
				height: 72rpx;
				line-height: 72rpx;
				white-space: nowrap;
				padding: 0 64rpx 0 24rpx;
				box-sizing: border-box;
				border-radius: 10rpx;
				color: #444;
				position: relative;
				font-size: 28rpx;
				overflow: hidden;

				.ic_down {
					position: absolute;
					right: 0;
					top: 0;
					width: 64rpx;
					height: 64rpx;
					background: #f7f7f8;
				}
			}
		}

		.submit {
			width: 100%;
			background: #fff;
			padding: 50rpx 0;
			box-sizing: border-box;

			.btn-submit {
				width: 100%;
				height: 84rpx;
				line-height: 84rpx;
				letter-spacing: 4rpx;
				background: #04BABE;
				color: #fff;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}
</style>